#ifndef REGISTRATION_LIB_H
#define REGISTRATION_LIB_H

#include "Registration.h"
#include "Student.h"
#include "Student_lib.h"
#include "Course.h"
#include "course_lib.h"
#include <cstring>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <sstream>

void Add_registration(string s, Registration[] l, int &numberRegistration){
    string temp, a_sid;
    int a_lid, a_stid;

    int mark = s.find(":");
    a_sid = s.substr(0,mark);

    temp = s.substr(mark+1);
    mark = temp.find(":");
    a_lid = atoi(temp.substr(0,mark).c_str());

    temp = temp.substr(mark+1);
    mark = temp.find(":");
    a_stid = atoi(temp.substr(0,mark).c_str());

    Registration Reg(a_sid, a_lid, a_stid);
    l[numberRegistration] = Reg;
    numberRegistration++;
}

void Read_Registration(string _file, Registration l[], int &numberRegistration){
    ifstream fin;
               fin.open(_file.c_str());
               if(!fin.is_open()){
                       cout<<"Cannot open file.\n";
                       exit(1);
               }else{
                              string s = "";
                              while (getline(fin, s)){
                                Add_registration(s, l, numberRegistration);
                              }
                              fin.close();
               }
}

void GetStudentsByCourse(string sid, int lid, string _file){
    int i = 0, j = 0, k = 0, m = 0;
    Registration l[1000];
    Student stu[100], stu_fil[100];
    Read_Registration(_file, l, i);
    ReadStudent("student.txt", stu, j);

    for (k = 0; k < i; k++){
        string r_sid = l[k].GetSID();
        int r_lid = l[k].GetLID();
        int r_stid = l[k].GetSTID();

        if ((r_sid == sid) && (r_lid == lid)){
            int n = Search_by_id(r_stid, stu, j);
            stu_fil[m] = stu[n];
            m++;
        }
    }

    WriteStudent("student_filtered_by_course.txt", stu_fil, m);
}

void GetCoursesByStudent(int stid, string _file){
    int i = 0, j = 0, k = 0, lid[100];
    string sid[100];
    Registration l[1000];
    Course c[100];
    Read_Registration(_file, l, i);

    for (j = 0; j < i; j++){
        int r_stid = l[j].GetSTID();

        if (r_stid == stid){
            lid[k] = l[j].GetLID();
            sid[k] = l[j].GetSID();
            c[k] = GetCourse(lid[k], sid[k]);
            k++;
        }
    }

    getCal(c, k);
}

#endif
